package pers.mtx.myapplication.service;

import android.app.Activity;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

import pers.mtx.myapplication.LogActivity;
import pers.mtx.myapplication.db.MyDatabaseHelper;
import pers.mtx.myapplication.model.Chatmodel.get.ReceiveMsgVo;
import pers.mtx.myapplication.model.Chatmodel.get.ReturnMsgVo;
import pers.mtx.myapplication.model.Chatmodel.get.SendMsgVo;
import pers.mtx.myapplication.model.Chatmodel.get.SucChatRecord;
import pers.mtx.myapplication.model.Chatmodel.get.msg.FileMsgVo;
import pers.mtx.myapplication.model.Chatmodel.get.msg.TextMsgVo;
import pers.mtx.myapplication.model.Chatmodel.put.LongConnectionChatDTO;
import pers.mtx.myapplication.model.Chatmodel.put.LongConnectionLoginDTO;
import pers.mtx.myapplication.util.SendChatUtil;


public class WebSocketService extends Service {

    public static String userId = "";

    private WebSocketBinder wsBinder = new WebSocketBinder();
    private MyDatabaseHelper dbHelper;
    private SQLiteDatabase db;
    public class WebSocketBinder extends Binder {
        public WebSocketService getService() {
            return WebSocketService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        userId = intent.getStringExtra("id");
        dbHelper = new MyDatabaseHelper(WebSocketService.this, 5);
        db = dbHelper.getWritableDatabase();
        return wsBinder;
    }

    @Override
    public void onCreate() {
        startSocket();
        super.onCreate();
    }

    private String TAG = "web_socket";
    private static ObjectMapper mapper = new ObjectMapper();
    WebSocketClient client;
    //转成的要操作的数据
    URI uri;
    //后台连接的url
    String address = "ws://192.168.1.109:8889/ws";


    public WebSocketService() {
    }

    public byte[] getFromAssets(String fileName) throws IOException {
        InputStream open = getAssets().open(fileName);
        byte[] bytes = new byte[open.available()];
        open.read(bytes);
//        InputStreamReader inputReader = new InputStreamReader(open);
//        BufferedReader bufReader = new BufferedReader(inputReader);
//        String line="";
//        StringBuilder Result= new StringBuilder();
//        while((line = bufReader.readLine()) != null)
//            Result.append(line);
        return bytes;
    }


    public void startSocket() {
        try {
            uri = new URI(address);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if (null == client || !client.isOpen()) {
            Log.d(TAG, "尝试建立: ");
            client = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    Log.d(TAG, "建立suc ");
                    try {
                        client.send(mapper.writeValueAsString(new LongConnectionLoginDTO(userId)));
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onMessage(String s) {
                    //后台返回的消息
                    Log.d(TAG, "返回: " + s);
                    try {
                        ReturnMsgVo msgVo = mapper.readValue(s.getBytes(StandardCharsets.UTF_8), ReturnMsgVo.class);
                        if (msgVo.getStatus().equals(ReturnMsgVo.RECEIVE_MSG)) {
                            ReceiveMsgVo receiveMsgVo = mapper.convertValue(msgVo.getMessage(), ReceiveMsgVo.class);
                            if (receiveMsgVo.getMsgType().equals(ReceiveMsgVo.TEXT)) {
                                TextMsgVo textMsgVo = mapper.convertValue(receiveMsgVo.getMessage(), TextMsgVo.class);

                                ContentValues values = new ContentValues();
                                values.put("send_time",textMsgVo.getTime());
                                values.put("sender_id",textMsgVo.getSenderId());
                                values.put("receiver_id",textMsgVo.getReceiverId());
                                values.put("message",textMsgVo.getMessage());
                                values.put("msg_type",5);
                                values.put("rb",textMsgVo.getRb());
                                values.put("msg_id",textMsgVo.getMsgId());
                                db.insertOrThrow("chat_record",null,values);


                                Intent setAction = new Intent().setAction("receiveSuc.mtx."+textMsgVo.getSenderId());
                                setAction.putExtra("chat", textMsgVo).putExtra("type",1);
                                sendBroadcast(setAction);
                            }
                            if (receiveMsgVo.getMsgType().equals(ReceiveMsgVo.FILE)) {
                                FileMsgVo fileMsg = mapper.convertValue(receiveMsgVo.getMessage(), FileMsgVo.class);

                                ContentValues values = new ContentValues();
                                values.put("send_time",fileMsg.getTime());
                                values.put("sender_id",fileMsg.getSenderId());
                                values.put("receiver_id",fileMsg.getReceiverId());
                                values.put("message",fileMsg.getUrl() + "_mtx_" + fileMsg.getFileName());
                                values.put("msg_type",5);
                                values.put("rb",fileMsg.getRb());
                                values.put("msg_id",fileMsg.getMsgId());
                                db.insertOrThrow("chat_record",null,values);


                                Intent setAction = new Intent().setAction("receiveSuc.mtx."+fileMsg.getSenderId());
                                setAction.putExtra("chat",fileMsg).putExtra("type",5);
                                sendBroadcast(setAction);

                            }
                        }
                        if (msgVo.getStatus().equals(ReturnMsgVo.SEND_SUCCESS)) {
                            SendMsgVo sendMsgVo = mapper.convertValue(msgVo.getMessage(), SendMsgVo.class);
                            LongConnectionChatDTO chatDTO = SendChatUtil.getInstanse().getMap().get(sendMsgVo.getChatId());
                            switch (chatDTO.getMsgType().intValue()){
                                case 1:
                                    SucChatRecord sucChatRecord = mapper.convertValue(sendMsgVo.getContent(), SucChatRecord.class);


                                    ContentValues values = new ContentValues();
                                    values.put("send_time",sucChatRecord.getTime());
                                    values.put("sender_id",sucChatRecord.getSenderid());
                                    values.put("receiver_id",sucChatRecord.getReceiverid());
                                    values.put("message",sucChatRecord.getMessage());
                                    values.put("msg_type",1);
                                    values.put("rb",sucChatRecord.getRb());
                                    values.put("msg_id",sucChatRecord.getMsgid());
                                    db.insertOrThrow("chat_record",null,values);


                                    Intent setAction = new Intent().setAction("sendSuc.mtx."+chatDTO.getReceiverId());
                                    setAction.putExtra("chat",sucChatRecord).putExtra("type",1);
                                    sendBroadcast(setAction);
                                    break;
                                case 5:
                                    FileMsgVo fileMsgVo = mapper.convertValue(sendMsgVo.getContent(), FileMsgVo.class);

                                    ContentValues valuesF = new ContentValues();
                                    valuesF.put("send_time",fileMsgVo.getTime());
                                    valuesF.put("sender_id",fileMsgVo.getSenderId());
                                    valuesF.put("receiver_id",fileMsgVo.getReceiverId());
                                    valuesF.put("message",fileMsgVo.getUrl() + "_mtx_" + fileMsgVo.getFileName());
                                    valuesF.put("msg_type",5);
                                    valuesF.put("rb",fileMsgVo.getRb());
                                    valuesF.put("msg_id",fileMsgVo.getMsgId());
                                    db.insertOrThrow("chat_record",null,valuesF);


                                    Intent setActionF = new Intent().setAction("sendSuc.mtx."+chatDTO.getReceiverId());
                                    setActionF.putExtra("chat",fileMsgVo).putExtra("type",5);
                                    sendBroadcast(setActionF);
                                    break;

                            }


                        }
                        if (msgVo.getStatus().equals(ReturnMsgVo.KICK_OFF)){
                            Context context = getBaseContext();
                            Intent intent = new Intent();
                            intent.putExtra("tag", 8);

                            intent.setClass(context, LogActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            context.startActivity(intent);
                            ((Activity)context).finish();
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {

                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                    Log.w(TAG, e.getMessage());
                }
            };
            client.connect();
        }
    }

    //向服务器发送消息
    public void sendMessage(Object s) {
        if (client == null || client.isClosed() || !client.isOpen()) {
            Log.d(TAG, "未建立实时通信");
            return;
        }
        try {
            Log.i(TAG, "发送: " + mapper.writeValueAsString(s));
            client.send(mapper.writeValueAsString(s));
        } catch (Exception e) {
            e.printStackTrace();
            startSocket();
        }
    }

    //关闭socket
    public void closeSocket() {
        if (client != null) {
            client.close();
            client = null;
        }
    }


}
